package com.jasperframework.boot.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
  * <p>  </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */
public class NoteUtil {

    /**
     * <p> 用于匹配类注释的内容   </p>
     * @param comment
     * @author daizhao
     * @date 2023/10/14 15:33
     */
    public static String extractComment(String comment) {
        // 匹配以 /** 开头、*/ 结尾的注释块
        String regex = "/\\*\\*(.|[\\r\\n])*?\\*/";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(comment);
        if (matcher.find()) {
            return matcher.group(0).trim();
        }
        return "";
    }

    /**
     * <p>匹配标签内的数据 </p>
     *
     * @param comment   匹配的内容
     * @param tag       匹配的标签，例如：p => <p>xxx</p>
     * @author daizhao
     * @date 2023/10/14 15:37
     */
    public static String extractTagData(String comment, String tag) {
        String regex = "<" + tag + ">(.*?)</" + tag + ">";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(comment);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return "";
    }

    /**
     * <p> 提取注释中 作者后面的 时间字符串 </p>
     * @param comment
     * @author daizhao
     * @date 2023/10/14 15:47
       @return
     */
    public static String extractDateStr(String comment){
        String regex = "@author.*?((\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2})|(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}))";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(comment);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }

    public static String replaceOldCommentFormat(String oldComment){

        String comment = NoteUtil.extractComment(oldComment);

        String p = NoteUtil.extractTagData(comment, "p");

        String dateStr = StringUtils.isEmpty(NoteUtil.extractDateStr(comment)) ? "2022/12/12 12:12" :  NoteUtil.extractDateStr(comment);

        String newComment = "/** \n" +
                "  * <p> " + p + " </p> \n" +
                "  * \n" +
                "  * @site https://miliqkdoc.motopa.cn/ \n" +
                "  * @author daizhao \n" +
                "  * @date " + dateStr + "\n" +
                "  */";
        return newComment;
    }
}
